import os
import requests
import time
import platform
from AppKit import NSWorkspace, NSScreen, NSImage, NSBitmapImageRep
from Foundation import NSURL

def download_bing_wallpaper():
    base_url = "https://www.bing.com"
    url = base_url + "/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US"
    response = requests.get(url)
    image_url = response.json()['images'][0]['url']
    image_url = base_url + image_url
    image_name = time.strftime("%Y-%m-%d") + ".jpg"
    # 获取当前工作目录并创建BingImg目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    bingimg_dir = os.path.join(current_dir, "BingImg")
    if not os.path.exists(bingimg_dir):
        os.mkdir(bingimg_dir)
    image_path = os.path.join(bingimg_dir, image_name)
    response = requests.get(image_url)
    with open(image_path, "wb") as f:
        f.write(response.content)
    print("图片已保存到本地！",image_path)
    return image_path

def set_wallpaper(image_path):
    image_url = NSURL.fileURLWithPath_(os.path.abspath(image_path))
    workspace = NSWorkspace.sharedWorkspace()
    screens = NSScreen.screens()
    options = {}
    image = NSImage.alloc().initWithContentsOfURL_(image_url)
    bitmap = NSBitmapImageRep.imageRepWithData_(image.TIFFRepresentation())
    for screen in screens:
        workspace.setDesktopImageURL_forScreen_options_error_(image_url, screen, options, None)
        print("第%d个显示器的壁纸已设置成功！" % (screens.index(screen) + 1))
        # try:
        #     properties = {NSWorkspaceDesktopImageFillColorKey: "0.0 0.0 0.0"}
        #     workspace.setDesktopImageOptions_forScreen_withImage_properties_error_(1, screen, bitmap, properties, None)
        #     print("第%d个显示器的填充颜色已设置成功！" % (screens.index(screen) + 1))
        # except AttributeError:
        #     pass
        
if __name__ == '__main__':
    if platform.system() == "Darwin":
        image_path = download_bing_wallpaper()
        set_wallpaper(image_path)
    else:
        print("当前操作系统不是macOS，无法设置壁纸！")